/*****************************************************************************************
**  Author:jxx 2022
**  QQ:283591387
**完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
**常用示例见：http://v2.volcore.xyz/document/vueDev
**后台操作见：http://v2.volcore.xyz/document/netCoreDev
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelHeader from "../goodsin_class/goodsInCom.vue"
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {  //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      this.setFiexdSearchForm(true);
      this.inventoryNumOff = true
      this.editFormOptions.forEach(option => {
        option.forEach(item => {
          if (item.field == "GoodsOut_client") {
            item.remote = true
            item.extra = {
              icon: "el-icon-zoom-in",
              text: "选择客户",
              style: "color:#3a8ee6;font-size:13px;cursor:pointer",
              click: () => {
                this.$refs.modelHeader.open()
              }
            }
          }
        })
      })


      //获取当前用户信息
      // let url = "api/q_goodsOut_class/getUserInfo"
      // this.http.post(url, {}, "").then(reslut => {
      //   try {
      //     this.user_Id = reslut.user_Id
      //   } catch (error) {
      //     console.error(error)
      //   }
      // })
      this.UpdateState = false //自定义用户编辑权限
      if (this.filterPermission("q_goodsOut_class", 'Update')) {
        this.UpdateState = true
      }
    },
    async onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      await this.detailOptions.buttons.splice(this.detailOptions.buttons.findIndex(item => item.name == "添加行"), 1)
      this.detailOptions.buttons.unshift({
        name: "选择商品",//按钮名称
        icon: 'el-icon-plus',//按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件
          this.$refs.modelHeader.detailOpen()
        }
      })
      this.detailOptions.beginEdit = (row, column, index) => {
        //库位下拉框----
      
        if (this.currentAction != 'Add' && !this.statusOff) {
          return false
        }
        if (this.currentAction == 'Add'){
          //可以继续
        }else if(this.currentAction == 'Update'&& !this.statusOff ||  !this.user_id_boole){
          return false
        }
        this.detailOptions.columns.forEach(item => {
          if (item.field == "WHSE_name") {

            let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.GoodsOutList_sub}`
            item.bind.data.forEach(d => {
              d.hidden = true
            })
            this.http.post(selectUrl, {}, "").then(reslut => {
              item.bind.data.forEach(d => {
                d.hidden = true
              })
              item.bind.data.forEach(d => {
                reslut.rows.forEach(j => {
                  if (d.key == j.WHSE_no) {
                    d.hidden = false
                  }
                })
              })
            })

          }
        })
        //--end
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        setTimeout(() => {
          let testInputDom = rows[index].querySelectorAll("td")[4].querySelector("input")
          testInputDom.addEventListener("keyup", (e) => {
            //在这里去请求判断库存数量
            if (+e.target.value) {
              if (row.WHSE_name) {
                // this.getInventoryNum(row, e.target.value)
                let url = `api/q_goods_inventory/getgoodsquantity?kw=${row.WHSE_name}&bm=${row.GoodsOutList_sub}`
                this.http.post(url, {}, "").then(({ rows }) => {
                  try {

                    if (typeof rows[0] == "object") {
                      let data = rows[0]
                      let off = +data.goods_inventory_quantity < + e.target.value || e.target.value == undefined
                      if (off) {
                        this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
                        e.target.blur()
                        setTimeout(() => {
                          row.GoodsOutList_num = null
                          setTimeout(() => {
                            e.target.focus()
                          }, 0)
                        }, 0)
                      }
                    } else if (rows[0] == null) {
                      this.$message.error("此商品在该库位暂无库存")
                      e.target.blur()
                      setTimeout(() => {
                        row.GoodsOutList_num = null
                        setTimeout(() => {
                          e.target.focus()
                        }, 0)
                      }, 0)
                    }
                  } catch (error) {
                    console.log("错误", error);
                  }
                })
              }
            } else {
              this.$message.error("请出入数字")
            }
          })
        }, 0)
        return true
      },
        this.detailOptions.columns.forEach(x => {
          if (x.field == 'WHSE_name') {
            x.onChange = (column, row, tableData) => {
              if (column.GoodsOutList_num) {
                this.getInventoryNum(column, column.GoodsOutList_num)
              }
            }
          }
        })
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true;
    },
    addBeforeAsync(formData) {
      return this.getSummary(formData)
    },
    async getSummary(formData) {
      let detailRowData = this.$refs.detail.rowData
      let summaryPrc = 0
      let summaryNum = 0
      let num = 0
      await detailRowData.forEach(item => {
        summaryPrc += item.GoodsOutList_price * item.GoodsOutList_num
        summaryNum += +item.GoodsOutList_num
        if (item.GoodsOutList_sub && item.GoodsOutList_name && item.GoodsOutList_num && item.GoodsOutList_price && item.WHSE_name) num++
      })
      console.log("summaryNum", summaryNum);
      formData.mainData.GoodsOut_num = summaryNum
      formData.mainData.GoodsOut_money = summaryPrc
      if (detailRowData.length == num) {
        return true
      } else {
        this.$message.error("请正确选择商品")
        return false
      }
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
    async updateBeforeAsync(formData) {
      // let url = `api/q_goodsOut_class/audit?auditReason=&auditStatus=0`
      // await this.http.post(url, [formData.mainData.GoodsOut_Id], "").then(reslut => {
      //   try {
      //     console.log("成功",reslut);
      //   } catch (error) {
      //     console.log("错误", error);
      //   }
      // })
      return this.getSummary(formData)
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    detailRowClick({ row, column, event }) {
      //编辑弹出框从表table点击行选中当前行，没有从表的不用管
      // this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.currentAction == 'Add' || this.statusOff && this.user_Id == row.CreateID) {
        // if (this.currentAction == 'Add' || this.statusOff ) {
        if (column.property == "GoodsOutList_price" || column.property == "GoodsOutList_num" || column.property == "Remark") {
          let dom = event.target
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }

    },

    async modelOpenBefore(row) {
      this.user_id_boole =this.user_Id == row.CreateID
      if (this.currentAction != 'Add') {
        // this.boxButtons[0].hidden = true
        if (this.boxButtons[0]) {
          this.boxButtons[0].hidden = true
        }
        this.editFormOptions.forEach(item => {
          item.forEach(x => {
            this.detailOptions.buttons.forEach(item => {
              item.hidden = true
            })
            if (x.field == "GoodsOut_client" || x.field == "Remark") {
              x.extra = null
              x.disabled = true
            }
          })
        })
      }
      // 新建
      if (this.currentAction == 'Add') {
        this.getModuleStatus()
      } else if (this.currentAction == 'update' && this.UpdateState) {
        let url = "api/Sys_WorkFlow/getSteps?tableName=q_goodsOut_class"
        await this.http.post(url, [row.GoodsOut_Id], "").then(reslut => {
          try {
            this.statusOff = reslut.list[1].isCurrent
            if (this.statusOff && this.user_id_boole) {
              // if (this.statusOff ) {
              this.getModuleStatus()
            }
          } catch (error) {
            console.log("错误", error);
          }
        })
      }

    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
      // this.editFormOptions.forEach(item => {
      //   item.forEach(x => {
      //     if (this.currentAction == 'Add') {
      //       this.detailOptions.buttons.forEach(item => {
      //         item.hidden = false
      //       })
      //       if (x.field == "Remark") {
      //         x.disabled = false
      //       }
      //     } else {
      //       this.detailOptions.buttons.forEach(item => {
      //         item.hidden = true
      //       })
      //       if (x.field == "Remark") {
      //         x.disabled = true
      //       }
      //     }
      //   })

      // })
      //------------分割线

    },
    async getModuleStatus() {
      this.boxButtons[0].hidden = false
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          this.detailOptions.buttons.forEach(item => {
            item.hidden = false
          })
          if (x.field == "GoodsOut_client") {
            x.extra = {
              icon: "el-icon-zoom-in",
              text: "选择客户",
              style: "color:#3a8ee6;font-size:13px;cursor:default",
              click: () => {
                this.$refs.modelHeader.open()
              }
            }
          }

          if (x.field == "GoodsOut_client" || x.field == "Remark") {
            x.disabled = false
          }
        })
      })
    },
    async getInventoryNum(rowObj, val) {
      let url = `api/q_goods_inventory/getgoodsquantity?kw=${rowObj.WHSE_name}&bm=${rowObj.GoodsOutList_sub}`
      await this.http.post(url, {}, "").then(({ rows }) => {
        try {
          if (typeof rows[0] == "object") {
            let data = rows[0]
            let off = +data.goods_inventory_quantity < + val || val == undefined
            if (off) {
              this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
              setTimeout(() => {
                rowObj.GoodsOutList_num = null
              }, 0)
            }
          } else if (rows[0] == null) {
            this.$message.error("此商品在该库位暂无库存")
            rowObj.GoodsOutList_num = null
          }
        } catch (error) {
          console.log("错误", error);
        }

      })
    }
  }
};
export default extension;
